<?php
/**
 * User: day
 * Date: 2018/08/07
 * Time: 23:42
 */

namespace App\Services\ThirdAPI;


use App\Models\PartnerConfig;
use common\utils\RedisKeys;
use App\Models\Order;
use App\Models\Game;
use common\utils\SysCode;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use common\enum\CommonEnum;

class SGAPIService {
    protected $apiName  = 'SG';
    protected $host     = 'https://api-egame-staging.sgplay.net';

    /**
     * 拉取第三方游戏SG的玩家注单数据
     * @param int $startTime 抓取时间段的开始时间
     * @param int $endTime 抓取时间段的结束时间
     * @return string|unknown
     */
    public function getSGOrders($startTime, $endTime) {
        Log::info("SG 获取注单：" . date("Y-m-d H:i:s", $startTime) . " - " . date("Y-m-d H:i:s", $endTime));
        Log::info("SG 获取注单：" . $startTime.' - '.$endTime);
        $url = config('app.rpcserver') . "/api/getOrders";
        $res = GameApiService::request($url, 'get', [
            'api_name' => 'SG',
            'start_time' => $startTime,
            'end_time' => $endTime,
        ]);
        return $res;
    }

    /**
     * 更新sg游戏列表
     * @return array|bool
     */
    public function getSGGameNames()
    {
        $data = Game::where(['partner_name' => $this->apiName, 'status' => 1])->get()->toArray();
        $needUpdate = Redis::set(RedisKeys::SG_LOCK_GAMES, date("Y-m-d H:i:s"), 'nx', 'ex', 24 * 60 * 60);
        if (!$data || $needUpdate) {
            $data = $this->getSGGameList();
        }
        $games = [];
        foreach ($data as $game) {
            $games[$game['game_code']] = $game['name'];
        }
        return $games;
    }

    /**
     * 获取游戏列表
     */
    public function getSGGameList() {
        $url = config('app.rpcserver') . "/api/getGameList";
        $res = GameApiService::request($url, 'get', ['api_name' => $this->apiName]);
        if(!$res){
            Redis::del(RedisKeys::SG_LOCK_GAMES);
            $msg = "SG 更新游戏列表失败，response:".json_encode($res);
            Log::error($msg);
            return error_exit(SysCode::INTERNAL_SERVER_ERROR, $msg);
        }
        $currentData = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $formatData = [];
        foreach ($currentData as $value) {
            $formatData[$value['game_code']] = $value;
        }
        $insertData = $openGames = [];
        $partnerInfo = GameApiService::getApiPartnerInfoByName($this->apiName);
        foreach ($res as $k => $value) {
            //新增的游戏
            if (empty($formatData[$value['gameCode']])) {
                $insertData[] = array(
                    'partner_id' => $partnerInfo['id'],
                    'game_type' => CommonEnum::GAME_EGAME,
                    'partner_name' => $partnerInfo['name'],
                    'name' => $value['gameName'],
                    'img_url' => $this->host.$value['thumbnail'],
                    'game_code' => $value['gameCode'],
                    'type' => 'slot',
                    'extend'=> json_encode($value)
                );
                unset($res[$k]);
            }
            //检查维护状态的游戏是否开启
            if(isset($formatData[$value['gameCode']]) && $formatData[$value['gameCode']]['status'] == 0){
                $openGames[] = $value['gameCode'];
            }
        }
        $maintainGames = array_diff(array_column($currentData, 'game_code'), array_column($res, 'gameCode'));
        if (count($insertData) > 0) {
            GameApiService::saveGame($insertData);
            Log::error("SG 新增游戏:".json_encode($insertData));
        }
        //处于维护状态的游戏
        if($maintainGames){
            Game::whereIn('game_code', array_values($maintainGames))
                ->update([
                'status' => 0
                ]);
            Log::error("SG 处于维护状态的游戏:".json_encode($maintainGames));
        }
        //处于维护开启状态的游戏
        if($openGames){
            Game::whereIn('game_code', array_values($maintainGames))
                ->update([
                'status' => 0
                ]);
            Log::error("SG 处于维护状态的游戏:".json_encode($maintainGames));
        }
        $gameLists = Game::where(['partner_name' => $this->apiName, 'status' => 1])->get()->toArray();
        return $gameLists;
    }

    /**
     * 更新奖金池
     */
    public function getBonusPool()
    {
        $url = config('app.rpcserver') . "/api/getBonusPool";
        //sg只有获取所有奖池列表接口，没有单独查询指定奖池接口
        $res = GameApiService::request($url, 'get', ['api_name' => $this->apiName, "game_code" => 0]);
        if(!$res){
            $msg = "SG 更新奖池失败，response:".json_encode($res);
            Log::error($msg);
            return error_exit(SysCode::INTERNAL_SERVER_ERROR, $msg);
        }
        $updateData = $jackpool = [];
        $jackpool = array_column($res, 'amount', 'name');
        $gameLists = Game::where(['partner_name' => $this->apiName])->get()->toArray();

        $totalJackpot = 0;
        foreach($gameLists as $game){
            $extend = json_decode($game['extend'], true);
            //过滤没有奖池的游戏(因为jackpotCode与奖池接口返回的code对应不上,故使用jackpotName)
            if(!isset($extend['jackpotName'])) continue;
            if(!isset($jackpool[$extend['jackpotName']]))  continue;
            //拼接更新的数据
            $jackpotName = $extend['jackpotName'];
            $amount = round(amount_format($jackpool[$extend['jackpotName']],true));
            $totalJackpot += $amount;
            if(isset($updateData[$jackpotName])){
                array_push($updateData[$jackpotName]['ids'], $game['id']);
            }else{
                $updateData[$jackpotName] = [
                    'ids' => [$game['id']],
                    'update' => ['jackpot' => $amount]
                ];
            }
        }
        Log::info('更新奖池：', $updateData);

        //更新奖金池
        foreach ($updateData as $value){
            Game::whereIn('id', $value['ids'])->update($value['update']);
        }
        //总金额
        PartnerConfig::where('partner_id', 17)->update(['jackpot' => $totalJackpot]);
    }
}
